import {
	url
} from "./url.js"
export default {
	// 全局配置
	common: {
		baseUrl: url,
		header: {
			'Content-Type': 'application/json;charset=UTF-8',
			'Content-Type': 'application/x-www-form-urlencoded'
		},
		data: {},
		method: 'GET',
		dataType: 'json'
	},

	// 请求 返回promise
	request(options = {}) {
		// 组织参数
		options.url = this.common.baseUrl + options.url
		options.header = options.header || this.common.header
		options.data = options.data || this.common.data
		options.method = options.method || this.common.method
		options.dataType = options.dataType || this.common.dataType


		// 请求
		return new Promise((res, rej) => {

			// 请求之前... todo
			// // 请求中...
			uni.request({
				...options,
				success: (result) => {
					return res(result);
					// 返回原始数据 
					if (options.native) {
						return res(result)
					}
					// 服务端成功
					else if (result.data.statusCode == 200) {
						let data = result.data.data
						res(result)
					} else {
						return rej(result.data || '系统错误')
					}
				},
				fail: (error) => {
					uni.showToast({
						title: JSON.stringify(error),
						icon: 'none'
					});
					return rej()
				}
			});
		}).catch((e) => {});
	},
	// get请求
	get(url, data = {}, options = {}) {
		options.url = url
		options.data = data
		options.method = 'GET'
		return this.request(options)
	},
	// post请求
	post(url, data = {}, options = {}) {
		options.url = url
		options.data = data
		options.method = 'POST'
		return this.request(options)
	},
	// delete请求
	del(url, data = {}, options = {}) {
		options.url = url
		options.data = data
		options.method = 'DELETE'
		return this.request(options)
	},
	// options请求
	options(url, data = {}, options = {}) {
		options.url = url
		options.data = data
		options.method = 'options'
		return this.request(options)
	},
	// put请求
	put(url, data = {}, options = {}) {
		options.url = url
		options.data = data
		options.method = 'put'
		return this.request(options)
	},
	// head请求
	head(url, data = {}, options = {}) {
		options.url = url
		options.data = data
		options.method = 'head'
		return this.request(options)
	},
	// trace请求
	trace(url, data = {}, options = {}) {
		options.url = url
		options.data = data
		options.method = 'trace'
		return this.request(options)
	},
	// connect请求
	connect(url, data = {}, options = {}) {
		options.url = url
		options.data = data
		options.method = 'connect'
		return this.request(options)
	},
}
